//app.js
App({
	siteInfo: require('siteinfo.js'),
	util: require("cqdx_communist/js/util.js"),
	globalData: {
		userInfo: []
	},

	onLaunch() {
		if (Object.keys(this.globalData.userInfo).length) {
    		console.log('已经有用户信息');
    	} else {
    		wx.login({
    			success: (res) => {
    				this.util.request({
    					url: 'entry/wxapp/Code',
    					data: {
    						code: res.code
    					},
    					success: (cb) => {
    						let openId = JSON.parse(cb.data.data.res).openid;
							this.globalData.userInfo.openId = openId;
							this.getuserinfo(openId)
    					}
    				})
    			}
    		})
    	}
	},

	// 自定义函数
	getuserinfo(openId) {
		let that = this;
		wx.showLoading({
			title: '加载中...',
			mask: true,
		})
		wx.getUserInfo({
			success: (res) => {
				console.log(res)
				wx.hideLoading();
				let data = {
					openid: this.globalData.userInfo.openId,
					avatarurl: res.userInfo.avatarUrl,
					nickname: res.userInfo.nickName,
					gender: res.userInfo.gender
				}
				this.util.request({
					url: 'entry/wxapp/UserInfo',
					data: data,
					success: (cb) => {
						console.log(cb)
					}
				})
			},
			fail: () => {
				wx.hideLoading();
				that.getauth();
			}
		})
	},
	getauth() {
		let that = this;
		wx.showModal({
			title:  '获取信息失败',
			content:'请允许授权以便为您提供给服务',
			success: (res) => {
				if (res.confirm) {
					wx.openSetting({
						success: (res) => {
							that.getUserinfo();
						},
						fail: (res) => {
							that.getauth();
						}
					})
				} else if (res.cancel) {
					that.getauth();
				}
			}
		})
	}
})